package service

import (
	"chat/log"
	"chat/models"
	"chat/utils"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"go.uber.org/zap"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func SendMsg(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Error("websocket connection error: ", zap.String("error", err.Error()))
	}
	defer conn.Close()
	err = handleMsg(conn, c)
	if err != nil {
		log.Error("websocket connection error: ", zap.String("error", err.Error()))
	}
	log.Info("websocket connection>>>>>>>")
}

func handleMsg(ws *websocket.Conn, c *gin.Context) error {
	msg, err := utils.Subscribe(c, utils.PublishKey)
	if err != nil {
		log.Error("websocket connection error: ", zap.String("error", err.Error()))
	}
	tm := time.Now().Format("2006-01-02 15:04:05")
	m := fmt.Sprintf("[ws][%s]:%s", tm, msg)
	err = ws.WriteMessage(1, []byte(m))
	return err
}

func SendUserMsg(c *gin.Context) {
	models.Chat(c.Writer, c.Request)
}

func SearchFriends(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("userId"))
	users := models.SearchFriend(uint(id))
	utils.RespOkList(c.Writer, users, len(users))
}

func ReadMessage(c *gin.Context) {
	form := c.Query("form_id")
	target := c.Query("target_id")
	if err := models.UpdateReadStatus(form, target); err != nil {
		utils.RespFail(c.Writer, "网络错误")
		return
	}
	utils.RespOk(c.Writer, nil, "")
}
